<template>
  <div class="list">
    <div style="width: 100%; height: 100%" id="mapContainer"></div>
    <iframe id="geoPage" width=0 height=0 frameborder=0  style="display:none;" scrolling="no"
        src="https://apis.map.qq.com/tools/geolocation?key=WVRBZ-RMI6R-S46WU-WARXB-6V4WO-UWBIO&referer=myapp">
    </iframe>
  </div>
</template>
<script>
var wx = require('weixin-js-sdk');
// 以下代码为基于DOMOverlay实现聚合点气泡
function ClusterBubble(options) {
  TMap.DOMOverlay.call(this, options);
}

ClusterBubble.prototype = new TMap.DOMOverlay();

ClusterBubble.prototype.onInit = function (options) {
  this.content = options.content;
  this.position = options.position;
};

// 销毁时需要删除监听器
ClusterBubble.prototype.onDestroy = function () {
  this.dom.removeEventListener("click", this.onClick);
  this.removeAllListeners();
};

ClusterBubble.prototype.onClick = function () {
  this.emit("click");
};

// 创建气泡DOM元素
ClusterBubble.prototype.createDOM = function () {
  var dom = document.createElement("div");
  dom.classList.add("clusterBubble");
  dom.innerText = this.content;
  dom.style.cssText = [
    "width: " + (40 + parseInt(this.content) * 2) + "px;",
    "height: " + (40 + parseInt(this.content) * 2) + "px;",
    "line-height: " + (40 + parseInt(this.content) * 2) + "px;",
  ].join(" ");

  // 监听点击事件，实现zoomOnClick
  this.onClick = this.onClick.bind(this);
  // pc端注册click事件，移动端注册touchend事件
  dom.addEventListener("click", this.onClick);
  return dom;
};

ClusterBubble.prototype.updateDOM = function () {
  if (!this.map) {
    return;
  }
  // 经纬度坐标转容器像素坐标
  let pixel = this.map.projectToContainer(this.position);

  // 使文本框中心点对齐经纬度坐标点
  let left = pixel.getX() - this.dom.clientWidth / 2 + "px";
  let top = pixel.getY() - this.dom.clientHeight / 2 + "px";
  this.dom.style.transform = `translate(${left}, ${top})`;

  this.emit("dom_updated");
};

window.ClusterBubble = ClusterBubble;
export default {
  data() {
    return {
      zoom: 12,
      geometriesData: [],
      map: null,
    };
  },
  async mounted() {
    // 1，初始化腾讯地图
    this.geolocation = new qq.maps.Geolocation(
      "WVRBZ-RMI6R-S46WU-WARXB-6V4WO-UWBIO", //KIVBZ-PBPRI-IQ3GI-5UZ5S-7BHEV-3VBFJ 久其
      "myapp"
    );
    // 2，并且开始定位
    this.getMyLocation();
    // window.addEventListener('message', function(event) {
    //     // 接收位置信息
    //     var loc = event.data;
    //     console.log('location', loc);
    // }, false);
    // this.init();
  },
  created() {
    var param = window.location.href.split("?")[1]
    var query = this.parseQuery(param)
    this.memberId = query.memberId || ''
    // console.log('----',query.memberId)
  },
  methods: {
    // 获取小程序传入的参数
    parseQuery(query) {
				var reg = /([^=&\s]+)[=\s]*([^=&\s]*)/g;
				var obj = [];
				while (reg.exec(query)) {
					obj[RegExp.$1] = RegExp.$2;
				}
				return obj;
			},
    // 获取点数组
    havGeometriesData() {
      return new Promise((resolve, reject) => {
          // let params = {
          //   city: "北京市",
          //   latitude: 40.034326,
          //   longitude: 116.294169,
          // };
          // this.$http.post("/api/member/associatorManage/nearAlumni", params).then(
          //   (res) => {},
          //   (error) => {}
          // );
        let geometriesData = [];
        // 模拟的数据
        for (let i = 0; i < 20; i++) {
          if (i <= 10) {
            geometriesData.push({
              id: "demo1-" + i,
              styleId: "marker",
              position: new TMap.LatLng(
                39.953416 + Math.random(0, 1) * i * 0.002,
                116.480945 + Math.random(0, 1) * i * 0.002
                // 22.316555+ Math.random(0, 1) * i * 0.002,                        
                // 114.174328 + Math.random(0, 1) * i * 0.002
              ),
              icon: "https://huiyixing.dakabg.com/group1/M00/05/03/CgIlOmafd2qAU76DAAALQB5ZNEk21.jpeg",
              properties: {
                title: "marker" + i,
              },
            });
          } else {
            geometriesData.push({
              id: "demo1-" + i,
              styleId: "marker",
              position: new TMap.LatLng(
                39.953416 + Math.random(0, 1) * i * 0.002,
                116.480945 + Math.random(0, 1) * i * 0.002
              ),
              icon: "https://huiyixing.dakabg.com/group1/M00/05/03/CgIlOmajH5SARJt_AAAB9n-YQE8627.png",
              properties: {
                title: "marker" + i,
              },
            });
          }
        }
        // console.log("----", geometriesData);
        resolve(geometriesData);
      });
    },
    getMyLocation() {
      this.geolocation.getLocation(this.showPosition, this.errorPosition); //开启定位
    },
    errorPosition(res){
      console.log("定位失败",res);
    },
   async showPosition(position) {
      console.log("定位成功");
      this.longitude = position.lng;
      this.latitude = position.lat;
      this.address =
      position.city + position.province + position.addr;
      alert(`${position.lng,position.lat,position.addr}`)
      console.log("定位成功",position);
      // 获取点数组
      this.geometriesData = await this.havGeometriesData();
      // 定位成功后开始绘制地图
      this.init();
    },
    // 移除默认的比例尺 指南针
    removeControl() {
      this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE); //移除腾讯地图比例尺
      this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION); //移除腾讯地图旋转控件
      //移除腾讯地图缩放控件
      this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);
    },
    // 创建点聚合实例
    createMarker() {
      let map = this.map;
      let geometriesData = this.geometriesData;
      // 标记点样式
      const markersStyle = {
        width: 30,
        height: 30,
        anchor: { x: 17, y: 21 },
        // 'src': require('@/assets/img/online.png'),
        color: "rgba(0, 0, 0, 0)", // 标注点文本颜色
        size: 22, // 标注点文本文字大小
        offset: { x: 0, y: -26 }, // 标注点文本文字基于direction方位的偏移属性
      };
      // 生成点标记的样式数据
      var MkStyles = {};
      geometriesData.forEach((item) => {
        MkStyles[item.id] = new TMap.MarkerStyle({
          ...markersStyle,
          src:
            item.icon ||
            "https://huiyixing.dakabg.com/group1/M00/05/03/CgIlOmafd2qAU76DAAALQB5ZNEk21.jpeg",
        });
      });
      // 聚合物设置
      var markerCluster = new TMap.MarkerCluster({
        id: "cluster",
        map: map,
        enableDefaultStyle: false, // 启用默认样式
        minimumClusterSize: 2, // 形成聚合簇的最小个数
        geometries: geometriesData, //点数组
        zoomOnClick: true, // 点击簇时放大至簇内点分离
        gridSize: 60, // 聚合算法的可聚合距离
        averageCenter: false, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
        maxZoom: 16, // 采用聚合策略的最大缩放级别
      });
      var clusterBubbleList = [];
      var markerGeometries = [];
      var marker = null;
      // 监听聚合簇变化
      markerCluster.on("cluster_changed", function (e) {
        // 销毁旧聚合簇生成的覆盖物
        if (clusterBubbleList.length) {
          clusterBubbleList.forEach(function (item) {
            item.destroy();
          });
          clusterBubbleList = [];
        }
        markerGeometries = [];
        // 根据新的聚合簇数组生成新的覆盖物和点标记图层
        var clusters = markerCluster.getClusters();
        clusters.forEach(function (item) {
          if (item.geometries.length > 1) {
            let clusterBubble = new ClusterBubble({
              map,
              position: item.center,
              content: item.geometries.length,
            });
            clusterBubble.on("click", () => {
              map.fitBounds(item.bounds);
            });
            clusterBubbleList.push(clusterBubble);
          } else {
            const data = item.geometries[0];
            markerGeometries.push({
              ...data,
              position: item.center,
              styleId: data.id,
            });
          }
        });
        if (marker) {
          // 已创建过点标记图层，直接更新数据
          marker.setGeometries(markerGeometries);
        } else {
          marker = new TMap.MultiMarker({
            map,
            styles: MkStyles,
            geometries: markerGeometries,
          });
          // 触发marker点击事件
          marker.on("click", (res) => {
            console.log("----", res);
          });
        }
      });
    },
    init() {
      // lat lng中心点坐标
      let lat = this.latitude;
      let lng = this.longitude;
      var drawContainer = document.getElementById("mapContainer");
      var center = new TMap.LatLng(lat, lng); //设置中心点坐标
      this.map = new TMap.Map(drawContainer, {
        zoom: this.zoom,
        pitch: 0,
        center: center,
        draggable: true,
        scrollable: true,
        mapStyleId: "style 1",
      });
      setTimeout(() => {
        this.map.zoomTo(18);
      }, 3000);
      // 移除默认配置
      this.removeControl();
      // 创建点聚合实例
      this.createMarker();
    },
  },
};
</script>
  
  <style scoped lang="less">
.list {
  height: 100%;
  width: 100%;
}
/deep/ .clusterBubble {
  border-radius: 50%;
  color: #fff;
  font-weight: 500;
  text-align: center;
  opacity: 0.88;
  background-image: linear-gradient(139deg, #4294ff 0%, #295bff 100%);
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2);
  position: absolute;
  top: 0px;
  left: 0px;
}
</style>
  